package Leetcode_Second_Brush;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Solution210 {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        Map<Integer, Integer> indegree = new HashMap<>();
        Map<Integer, List<Integer>> connections = new HashMap<>();

        for (int i = 0; i < numCourses; i++) {
            indegree.put(i, 0);
        }

        for (int i = 0; i < prerequisites.length; i++) {
            indegree.put(prerequisites[i][0], indegree.get(prerequisites[i][0]) + 1);
            connections.computeIfAbsent(prerequisites[i][1], k -> new ArrayList<Integer>()).add(prerequisites[i][0]);
        }

        Deque<Integer> queue = new LinkedList<>();
        List<Integer> result = new ArrayList<>();

        for (Integer i : indegree.keySet()) {
            if (indegree.get(i) == 0)
                queue.offer(i);
        }

        while (!queue.isEmpty()) {
            int i = queue.poll();
            result.add(i);
            List<Integer> connection = connections.getOrDefault(i, Collections.emptyList());
            for (int j : connection) {
                indegree.put(j, indegree.get(j) - 1);
                if (indegree.get(j) == 0)
                    queue.offer(j);
            }
        }

        for (int key : indegree.keySet()) {
            if (indegree.get(key) > 0)
                return new int[] {};
        }

        return result.stream().mapToInt(Integer::intValue).toArray();
    }
}

